package system

import (
	"context"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"go.uber.org/zap"
)

type LoginRecordService struct{}

// CreateLoginRecord 创建登录记录
func (l *LoginRecordService) CreateLoginRecord(userID uint, ip, userAgent string, loginResult bool, reason string) {
	// 解析IP地理位置
	location, err := utils.GetIPLocation(ip)
	if err != nil {
		global.GVA_LOG.Error("解析IP地理位置失败", zap.String("ip", ip), zap.Error(err))
		// 即使解析失败，我们仍然需要记录登录信息
		location = &utils.IPLocation{}
	}

	// 创建登录记录
	record := system.SysLoginRecord{
		UserID:   userID,
		IP:       ip,
		Country:  location.Country,
		Province: location.Province,
		City:     location.City,
		UA:       userAgent,
		LoginAt:  time.Now(),
		Result:   &loginResult,
		Reason:   reason,
	}

	// 插入数据库
	if err := global.GVA_DB.Create(&record).Error; err != nil {
		global.GVA_LOG.Error("创建登录记录失败", zap.Error(err))
	}
}

// CreateLoginRecordWithContext 创建带上下文的登录记录
func (l *LoginRecordService) CreateLoginRecordWithContext(ctx context.Context, userID uint, ip, userAgent string, loginResult bool, reason string) {
	// 解析IP地理位置
	location, err := utils.GetIPLocation(ip)
	if err != nil {
		global.GVA_LOG.Error("解析IP地理位置失败", zap.String("ip", ip), zap.Error(err))
		// 即使解析失败，我们仍然需要记录登录信息
		location = &utils.IPLocation{}
	}

	// 创建登录记录
	record := system.SysLoginRecord{
		UserID:   userID,
		IP:       ip,
		Country:  location.Country,
		Province: location.Province,
		City:     location.City,
		UA:       userAgent,
		LoginAt:  time.Now(),
		Result:   &loginResult,
		Reason:   reason,
	}

	// 插入数据库
	if err := global.GVA_DB.WithContext(ctx).Create(&record).Error; err != nil {
		global.GVA_LOG.Error("创建登录记录失败", zap.Error(err))
	}
}

var LoginRecordServiceApp = new(LoginRecordService)
